<script setup lang="ts">
import {vAutoAnimate} from '@formkit/auto-animate/vue'
import {toTypedSchema} from '@vee-validate/zod'
import {useForm} from 'vee-validate'
import {h} from 'vue'
import * as z from 'zod'

import {Button} from '@/components/ui/button'
import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import {Input} from '@/components/ui/input'
import {toast} from "vue-sonner";
import {Textarea} from "@/components/ui/textarea";

const formSchema = toTypedSchema(z.object({
  name: z.string().min(2).max(50),
  description: z.string().min(0).max(200),
  summary: z.string().min(0).max(500),
}))

const {isFieldDirty, handleSubmit} = useForm({
  validationSchema: formSchema,
})

const onSubmit = handleSubmit((values) => {
  toast('Key has been created.', {
    title: 'You submitted the following values:',
    description: h('pre', {class: 'mt-2 w-[320px] rounded-md bg-slate-950 p-4'}, h('code', {class: 'text-white'}, JSON.stringify(values, null, 2))),
  })
  // TODO: do something with the values
})
</script>

<template>
  <form class="space-y-6" @submit="onSubmit">
    <FormField v-slot="{ componentField }" name="name" :validate-on-blur="!isFieldDirty">
      <FormItem v-auto-animate>
        <FormLabel>Name</FormLabel>
        <FormControl>
          <Input type="text" v-bind="componentField"/>
        </FormControl>
        <FormDescription>
          This is key display name.
        </FormDescription>
        <FormMessage/>
      </FormItem>
    </FormField>
    <FormField v-slot="{ componentField }" name="description" :validate-on-blur="!isFieldDirty">
      <FormItem v-auto-animate>
        <FormLabel>Description</FormLabel>
        <FormControl>
          <Input type="text" v-bind="componentField"/>
        </FormControl>
        <FormDescription>
          This is key display description.
        </FormDescription>
        <FormMessage/>
      </FormItem>
    </FormField>
    <FormField v-slot="{ componentField }" name="summary" :validate-on-blur="!isFieldDirty">
      <FormItem v-auto-animate>
        <FormLabel>Summary</FormLabel>
        <FormControl>
          <Textarea type="text" v-bind="componentField"/>
        </FormControl>
        <FormDescription>
          This is key display summary.
        </FormDescription>
        <FormMessage/>
      </FormItem>
    </FormField>

    <Button type="submit">
      Submit
    </Button>
  </form>
</template>
